package com.xuecheng.media.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.*;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalTime;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-04
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate vodTemplate;

    // 获取上传凭证
    @Override
    public ResponseResult vodToken(VodUploadDto dto) throws Exception {
        // 1.校验参数
        if (StrUtil.isBlank(dto.getTitle()) || StrUtil.isBlank(dto.getFileName())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        // 2.调用阿里云获取凭证
        CreateUploadVideoResponse response = vodTemplate.createUploadVideo(dto.getTitle(), dto.getFileName());
        // 3.封装vo
        VodUploadVo vo = BeanHelper.copyProperties(response, VodUploadVo.class);
        vo.setUserId(AuthInfoHolder.getUserId().toString()); // 设置上传人
        // 4.返回vo
        return ResponseResult.okResult(vo);
    }

    // 刷新上传凭证
    @Override
    public ResponseResult refreshToken(String videoId) throws Exception {
        // 1.校验参数
        if (StrUtil.isBlank(videoId)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        // 2.调用阿里云获取新凭证
        RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
        // 3.封装vo
        VodUploadVo vo = BeanHelper.copyProperties(response, VodUploadVo.class);
        vo.setUserId(AuthInfoHolder.getUserId().toString()); // 设置上传人id
        // 4.返回vo
        return ResponseResult.okResult(vo);
    }

    // 保存媒资
    @Override
    public ResponseResult saveMedia(MediaDto dto) throws Exception {
        // 1.dto -> media
        Media media = BeanHelper.copyProperties(dto, Media.class);
        // 2.补充基本字段
        media.setCreateDate(DateUtil.date()); // 创建时间
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS);
        // 3.根据fileId（vid）查询视频信息
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(dto.getFileId());
        GetPlayInfoResponse.PlayInfo playInfo = response.getPlayInfoList().get(0);
        String duration = playInfo.getDuration(); // 视频时长，单位：秒
        String playURL = playInfo.getPlayURL(); // 视频播放地址

        // 将字符串转float 转 long
        Float f = Float.parseFloat(duration);
        // 91秒 -> 01:31
        String time = LocalTime.MIN.plus(Duration.ofMinutes(f.longValue())).toString();

        // 4.补全视频字段
        media.setUrl(playURL);
        media.setTimelength(time);
        // 5.保存数据库
        this.save(media);
        return ResponseResult.okResult();
    }

    // 媒资分页查询
    @Override
    public ResponseResult findByPage(PageRequest params, MediaQueryDto dto) {
        // 1.构建条件
        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotBlank(dto.getFilename()), Media::getFilename, dto.getFilename());
        qw.eq(StrUtil.isNotBlank(dto.getType()),Media::getType ,dto.getType());
        qw.eq(StrUtil.isNotBlank(dto.getAuditStatus()),Media::getAuditStatus ,dto.getAuditStatus());
        // 2.构建分页
        Page<Media> page = new Page<>(params.getPageNo(), params.getPageSize());
        // 3.分页查询
        page = this.page(page, qw);
        // 4.media->vo
        List<Media> mediaList = page.getRecords();
        List<MediaVo> voList = BeanHelper.copyWithCollection(mediaList, MediaVo.class);
        // 5.返回分页结果
        return PageResponseResult.okResult(page.getTotal(), voList);
    }

    // 媒资预览
    @Override
    public ResponseResult preview(Long mediaId) throws Exception {
        // 1.查询媒资对象
        Media media = this.getById(mediaId);
        // 2.调用阿里云查询视频信息
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        // 3.取出最新播放地址
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        // 4.返回播放地址
        return ResponseResult.okResult(playURL);
    }



    // 媒资删除
    @Override
    public ResponseResult deleteMedia(Long mediaId) {
        // 1.先查媒资
        Media media = this.getById(mediaId);
        // 2.判断审核状态
        if (media.getAuditStatus().equals(MediaConstants.AUDIT_PASTED_STATUS)) {
           throw new BusinessException(ErrorCode.ERROR);
        }
        // 3.删除阿里云
        try {
            vodTemplate.deleteVideo(media.getFileId());
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        // 4.删除数据库
        boolean isSuccess = this.removeById(mediaId);
        if(!isSuccess){
            throw new BusinessException(ErrorCode.ERROR);
        }
        // 5.返回结果
        return ResponseResult.okResult();
    }


    // 媒资审核
    @Override
    public ResponseResult auditMedia(MediaAuditDto dto) {
        // 1.创建媒资对象
        Media media = new Media();
        // 3.设置三个参数
        media.setId(dto.getId());
        media.setAuditMind(dto.getAuditMind());
        media.setAuditStatus(dto.getAuditStatus());
        // 4.更新数据库
        this.updateById(media);
        // 5.返回结果
        return ResponseResult.okResult();
    }

    // 根据id查媒资播放地址
    @Override
    public ResponseResult findMedisUrl(Long mediaId) throws Exception {
        // 1.查询媒资对象
        Media media = this.getById(mediaId);
        String fileId = media.getFileId();
        // 2.根据fileId查询阿里云播放信息
        GetPlayInfoResponse infoResponse = vodTemplate.getPlayInfo(fileId);
        String playURL = infoResponse.getPlayInfoList().get(0).getPlayURL();
        // 3.封装vo
        ResourceVo vo = new ResourceVo();
        vo.setPlayUrl(playURL);
        // 4.返回结果
        return ResponseResult.okResult(vo);
    }
}
